package com.greate.shiro.springbootshirodemo.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.greate.shiro.springbootshirodemo.common.Constants;
import com.greate.shiro.springbootshirodemo.config.CustomCredentialsMatcher;
import com.greate.shiro.springbootshirodemo.config.JwtTokenUtils;
import com.greate.shiro.springbootshirodemo.config.TokenInfo;
import com.greate.shiro.springbootshirodemo.entity.SystemUser;
import com.greate.shiro.springbootshirodemo.service.SystemUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiSort;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zs
 * @since 2020-07-28
 */
@RestController
@RequestMapping("/user/")
@Api(tags = "用户模块", hidden = true)
@ApiSort(1)
public class SystemUserController {

	@Resource
	private SystemUserService systemUserService;

	@RequestMapping("login")
	@ApiOperation(value = "登录", httpMethod = "GET")
	public String login(
		@ApiParam(value = "用户名") @RequestParam(value = "username") String username,
		@ApiParam(value = "密码") @RequestParam(value = "password") String password
	) throws UnsupportedEncodingException, JsonProcessingException {

		String encryptPassword = CustomCredentialsMatcher.encrypt(password);

		SystemUser one = systemUserService.lambdaQuery()
			.eq(SystemUser::getUsername, username)
			.eq(SystemUser::getPassword, encryptPassword)
			.last(Constants.Sql.LIMIT_ONE)
			.one();

		if (one == null) {
			return "用户名，密码错误";
		}


		return JwtTokenUtils.sign(new TokenInfo(username, encryptPassword), 1000 * 60 * 60);
	}

	@RequiresPermissions("all")
//    @RequiresRoles("普通用户")
	@RequestMapping("test")
	@ApiOperation(value = "测试", httpMethod = "GET")
	@ApiImplicitParam(name = "token", value = "用户登录取得的 token", dataType = "String", paramType = "header", required = true)
	public String test() {
		return "success.";
	}

}

